package com.easyattendance.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.easyattendance.model.Section;
import com.easyattendance.model.Teacher;
import com.easyattendance.model.User;
import com.easyattendance.nls.UseProperties;
import com.easyattendance.services.AddSectionService;
import com.easyattendance.services.AddTeacherService;
import com.easyattendance.services.LoginService;
import com.easyattendance.services.ValidationsService;
import com.easyattendance.util.SecurePassword;


@WebServlet(name = "AddTeacherServlet", urlPatterns = { "/AddTeacherServlet" })
public class AddTeacherServlet extends HttpServlet {
	

	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {  
    	response.setContentType("text/html;charset=UTF-8");
		 PrintWriter out = response.getWriter();
		
        
        String actionType = request.getParameter("action_type");
        boolean createDispatcherFlag = false;
		boolean updateDispatcherFlag = false;
		Long teacherHomeNo= 0L;
        Long teacherMobile = 0L;
        
        AddTeacherService addTeacherService = new AddTeacherService();
        LoginService loginService = new LoginService();
        AddSectionService sectionService = new AddSectionService();
        ValidationsService validationsService = new ValidationsService();
        
        if(actionType.equals("create")) {
        	String teacherName = request.getParameter("teacher_fname");
            String teacherLName = request.getParameter("teacher_lname");
            String teacherEmail = request.getParameter("teacher_email");
            String teacherAddress = request.getParameter("teacher_address");
            String teacherPassword = request.getParameter("teacher_password");
            String teacherRepassword = request.getParameter("teacher_repassword");
            if(!request.getParameter("teacher_home_no").isEmpty()){
            	teacherHomeNo = Long.parseLong(request.getParameter("teacher_home_no"));
            }
            if(!request.getParameter("teacher_mobile").isEmpty()){
            	teacherMobile = Long.parseLong(request.getParameter("teacher_mobile"));
            }            
            String teacherGender = request.getParameter("gender_select");
            String teacherDOB = request.getParameter("teacher_dob");
            String teacherDOJ = request.getParameter("teacher_doj");
            String teacherSkills = request.getParameter("teacher_skills");
            int role_id=3; //Role_id for Teacher is 3
            
            if(teacherName.isEmpty() || teacherLName.isEmpty() || teacherEmail.isEmpty() || teacherAddress.isEmpty() || teacherPassword.isEmpty() || teacherRepassword.isEmpty() || teacherMobile < 999999999 || teacherGender.isEmpty() || teacherDOB.isEmpty() || teacherDOJ.isEmpty() || teacherSkills.isEmpty()){
	        	
            	request.setAttribute("null_values", "All * fields are required");
	        	createDispatcherFlag = true;
	        	
            }else{ 
            	
        		String validateName = validationsService.validateName(teacherName);
            	String validateLastname = validationsService.validateName(teacherLName);
		        String validateEmail = validationsService.validateEmailId(teacherEmail);
		        String validatePasswords = validationsService.validatePassword(teacherPassword);
		        boolean validateBothPasswords = validationsService.validateBothPasswords(teacherPassword, teacherRepassword);
		        
		        if(validateName.equals("Correct") && validateLastname.equals("Correct")) {
		        	if(validateEmail.equals("Correct")) {
		        		if(validatePasswords.equals("Correct") && validateBothPasswords) {
		        			
		        			String sectionEmailId =  (String) request.getSession().getAttribute("currentUser");//request.getParameter("dept_email_id");
		                    String secret_key = UUID.randomUUID().toString();
		                    
		                	Teacher newTeacher = new Teacher(teacherName,teacherLName, teacherEmail, teacherAddress);
		                    boolean res = addTeacherService.ifAlreadyExists(newTeacher);
		                    String ID=null;
		                    boolean result=false;
		                    
		        			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		        			java.util.Date teacherBirthDate = null;
		        			try {
		        					teacherBirthDate = format.parse(teacherDOB);
		        			} catch (ParseException e) {
		        					e.printStackTrace();
		        			}
		        			
		        			java.util.Date teacherJoinDate = null;
		        			try {
		        				teacherJoinDate = format.parse(teacherDOJ);
		        			} catch (ParseException e) {
		        					e.printStackTrace();
		        			}		                    
		        			
	        				if(!res) {
	                    	
		                    	//Add section for this teacher
		                    	Section section = sectionService.getSectionBySectionEmail(sectionEmailId);
		                    	String section_name=section.getSection_name().substring(0,3).toUpperCase();
		                    	boolean flag2 = sectionService.ifAlreadyExists(sectionEmailId);
		                    	
		                    	Properties labels = UseProperties.loadProperties("Attendance.properties");
		                    	//labels = UseProperties.incrementTeacherIdCounterValue(labels);
		                    	ID = section_name+"_"+UseProperties.getTeacherIdPrefix(labels)+addTeacherService.getTeacherIdValue(section_name,section.getSection_id());
		                    	
		                    	User newUser = new User(ID,role_id,SecurePassword.getHashValue(teacherPassword),teacherEmail,secret_key,false,true);
		                    	
		                    	// add login userid to this teacher
		                    	boolean flag = loginService.ifAlreadyExists(newUser);
		                    	
		                    	
		                    	if(!flag) {
		                    		if(flag2) {
		                    			loginService.addNewUser(newUser);
		                        		
		                        		Teacher teacher = new Teacher(ID, teacherName,teacherLName, teacherEmail, teacherAddress, teacherMobile, teacherHomeNo, false ,teacherSkills, teacherGender, teacherBirthDate, teacherJoinDate);
		                            	teacher.setUser(newUser);
		                            	teacher.setSection(section);
		                                result = addTeacherService.addTeacher(teacher);
		                    		}
		                    		else {
		                    			//decrement ID counter
		                    			labels = UseProperties.decrementTeacherIdCounterValue(labels);
		                    			request.setAttribute("sectionNotExists", "This Section does not exist.");
		                    			createDispatcherFlag = true;
		                    		}
		                    		
		                    	}
		                    	else {
		                    		labels = UseProperties.decrementTeacherIdCounterValue(labels);
		                    		request.setAttribute("userExists", "This User already exists.. change Email-id.");
		                    		createDispatcherFlag = true;
		                    	}            
	        				}
	        				else {
		                    	request.setAttribute("teacherExists", "Teacher already exists.. check Email-id entered.");
		                    	createDispatcherFlag = true;
		                    }
	                 
	            			if (result) {
	            				request.setAttribute("teacherAdded", "Teacher added Successfully.");
	            				createDispatcherFlag = true;
	        		        	addTeacherService.SendMail(teacherEmail);
	            			} else {
	            				request.setAttribute("teacherNotAdded", "Teacher not added.");
	            				createDispatcherFlag = true;
	            			}
		                  
		        			
		        		}
		        		else {//validate password
		        			request.setAttribute("validate_teacher_passwords", "Password not valid or Passwords do not match.");
				        	createDispatcherFlag = true;
		        		}
		        	}
		        	else {//validate email
		        		request.setAttribute("validate_teacher_email", validateEmail);
			        	createDispatcherFlag = true;
		        	}
		        }
		        else {//validate name
		        	request.setAttribute("validate_teacher_name", validateName);
		        	createDispatcherFlag = true;
		        }        		
            }//end of main else - if not null
          
            //Common error print and redirect.
			if(createDispatcherFlag) {
				RequestDispatcher rd = request.getRequestDispatcher("views/section/addTeacher.jsp");
		    	rd.forward(request, response);
			}
            	
           
        }
        else if(actionType.equals("update")){
        	
        	int i = Integer.parseInt(request.getParameter("i_value"));
        	
        	String teacherName = request.getParameter("teacher_fname"+i);
            String teacherLName = request.getParameter("teacher_lname"+i);
            String teacherEmail = request.getParameter("teacher_email"+i);
            String teacherAddress = request.getParameter("teacher_address"+i);
            
            teacherHomeNo = Long.parseLong(request.getParameter("teacher_home_no"+i));
            teacherMobile = Long.parseLong(request.getParameter("teacher_mobile"+i));
            String teacherSkills = request.getParameter("teacher_skills"+i);
            int role_id=3; //Role_id for Teacher is 3
            String sectionEmailId =  (String) request.getSession().getAttribute("currentUser");//request.getParameter("dept_email_id");
            String teacherGender = request.getParameter("teacher_gender_select"+i);
        	
        	Teacher teacher = addTeacherService.getTeacherByEmailId(teacherEmail);
        	teacher.setTeacher_address(teacherAddress);
        	teacher.setTeacher_name(teacherName);
        	teacher.setTeacher_lname(teacherLName);
        	teacher.setTeacher_mobile_no(teacherMobile);
        	teacher.setTeacher_resi_no(teacherHomeNo);
        	teacher.setTeacher_skills(teacherSkills);
        	teacher.setTeacher_gender(teacherGender);
        	
        	boolean res = addTeacherService.updateTeacher(teacher);
        	
        	if(res) {
        		//out.println("Teacher Updated Successfully");
        		request.setAttribute("teacherUpdated", "Teacher Updated Successfully.");
	        	RequestDispatcher rd = request.getRequestDispatcher("views/section/teacherSettings.jsp");
	        	rd.forward(request, response);
        		
        	}
        	else {
        		//out.println("Teacher NOT Updated Successfully");
        		request.setAttribute("teacherNotUpdated", "Teacher not Updated.");
	        	RequestDispatcher rd = request.getRequestDispatcher("views/section/teacherSettings.jsp");
	        	rd.forward(request, response);
        		
        	}
        }
        else if(actionType.equals("delete")) {
			int i = Integer.parseInt(request.getParameter("i_value"));
			String teacherId = request.getParameter("teacher_id"+i);
			//Section section = addSectionService.getSectionBySectionEmail(sectionEmail);
			
			Teacher thisTeacher = addTeacherService.getTeacherById(teacherId);
			if (thisTeacher.isClassTeacher()) {
				request.setAttribute("isClassTeacherDeleted", "This teacher cannot be deleted. Assign new class teacher in place of this class teacher");
	        	RequestDispatcher rd = request.getRequestDispatcher("views/section/teacherSettings.jsp");
	        	rd.forward(request, response);
			}
			
			boolean res = addTeacherService.deleteTeacher(teacherId);
			
			if(res){
				//out.println("Class deleted successfully");
				request.setAttribute("teacherDeleted", "Teacher deleted successfully.");
	        	RequestDispatcher rd = request.getRequestDispatcher("views/section/teacherSettings.jsp");
	        	rd.forward(request, response);
			}
			else {
				//out.println("Class CANNOT be deleted successfully");
				request.setAttribute("teacherNotDeleted", "Teacher Not deleted successfully.");
	        	RequestDispatcher rd = request.getRequestDispatcher("views/section/teacherSettings.jsp");
	        	rd.forward(request, response);
			}
		}
        else {
        	//out.println("Invalid action chosen.. Go back to select again");
        	request.setAttribute("invalidAction", "Invalid action chosen.");
        	RequestDispatcher rd = request.getRequestDispatcher("views/section/teacherSettings.jsp");
        	rd.forward(request, response);
        }
      
    }

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>
}
